package com.miya.system.configure;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * mybatis +配置
 *
 * @author Caixiaowei
 * @date 2022/02/16
 */
@Slf4j
@Configuration
public class MybatisPlusConfigure {

	/**
	 * 新的分页插件,一缓和二缓遵循mybatis的规则,
	 * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
	 */
	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		return interceptor;
	}
	@Bean
	public MetaObjectHandler metaObjectHandler() {
		return new MetaObjectHandler() {
			/**
			 * 插入元对象字段填充（用于插入时对公共字段的填充）
			 *
			 * @param metaObject 元对象
			 */
			@Override
			public void insertFill(MetaObject metaObject) {
				this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class);
				this.strictInsertFill(metaObject, "updatedTime", () -> LocalDateTime.now(), LocalDateTime.class);
			}

			/**
			 * 更新元对象字段填充（用于更新时对公共字段的填充）
			 *
			 * @param metaObject 元对象
			 */
			@Override
			public void updateFill(final MetaObject metaObject) {
				this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
			}
		};
	}
}
